#include "SrDemuxThread.h"

SrDemuxThread::SrDemuxThread()
    :m_movie_demux(NULL)
    , _vt(NULL)
    ,_at(NULL)
    ,_isExit(false)
{

}
SrDemuxThread::~SrDemuxThread()
{

}

bool SrDemuxThread::Open(const char *url, ISrVideoShow *show)
{
    _isExit = false;

    if (url == NULL)
    {
        return false;
    }

    if (!m_movie_demux)
    {
        m_movie_demux = new SrDemux();
    }

    // 打开解封装
    bool re = m_movie_demux->Open(url);
    if(!re)
    {
        qDebug("_demux->Open(url) failed!\n");
        return false;
    }

    if (!_vt)
    {
        _vt = new SrVideoThread();
    }
    if (!_at)
    {
        _at = new SrAudioThread();
    }

    // 打开视频解码器和处理线程
    if (!_vt->Open(m_movie_demux->CopyVPara(), show, m_movie_demux->_width, m_movie_demux->_height))
    {
        re = false;
        qDebug("_vt->Open failed!\n");
    }
    // 打开音频解码器和处理线程
    if (!_at->Open(m_movie_demux->CopyAPara(), m_movie_demux->_sampleRate, m_movie_demux->_channels))
    {
        re = false;
        qDebug( "_at->Open failed!\n");
    }

    qDebug( "SrDemuxThread::Open : \n");
    return re;
}
// 关闭线程清理资源
void SrDemuxThread::Close()
{
    _isExit = true;
    QThread::wait();

    if (_vt)
    {
        _vt->Close();
    }
    if (_at)
    {
        _at->Close();
    }

    delete _vt;
    delete _at;
    _vt = NULL;
    _at = NULL;

    m_movie_demux->Close();

    delete m_movie_demux;
    m_movie_demux = NULL;
}

// 启动所有线程
void SrDemuxThread::Start()
{
    QThread::start();
    if (_vt) _vt->start();
    if (_at) _at->start();
}

void SrDemuxThread::run()
{
    while (!_isExit)
    {

        if (!m_movie_demux)
        {
            msleep(5);
            continue;
        }


        // 音视频同步
        if (_vt && _at)
        {
            //把当前audio的播放时间给视频
            _vt->_syncPts = _at->audio_cur_pts;
        }


        AVPacket *pkt = m_movie_demux->Read();
        if (!pkt)
        {
            msleep(5);
            continue;
        }
        // 判断数据是音频
        if (m_movie_demux->IsAudio(pkt))
        {
            if(_at)
                _at->Push(pkt);
        }
        else // 视频
        {
            if (_vt)
                _vt->Push(pkt);
        }
    }
}
